<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
    <!-- 提示 -->
      <el-alert show-icon :closable="false" title="注意：只允许第三级分类设置相关参数！" type="warning"> </el-alert>
      <!-- 选择商品分类 -->
      <el-row class="cate-wrap">
        <el-col :span="3">选择商品分类：</el-col>
        <el-col :span="20"><el-cascader
          v-model="selectKeys"
          clearable
          :options="cateDefaultOptions"
          :props="{ expandTrigger: 'hover',  label: 'cat_name', value: 'cat_id'}"
          @change="handleChange"></el-cascader></el-col>
      </el-row>
      <!-- 参数 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
           <el-button type="primary" size="mini" :disabled="isBtn" @click="addParams">添加参数</el-button>
           <!-- 动态参数列表 -->
           <el-table :data="manyData" style="width: 100%" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(scope.row, i)">{{item}}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editParams(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
           </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
           <el-button type="primary" size="mini" :disabled="isBtn" @click="addParams">添加属性</el-button>
           <!-- 静态属性列表 -->
           <el-table :data="onlyData" style="width: 100%" stripe border>
             <el-table-column type="expand">
               <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(scope.row, i)">{{item}}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
             </el-table-column>
             <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
            <el-table-column label="操作">
              <template>
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editParams(scope.row)">>编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
           </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数按钮 -->
    <el-dialog :title=" '添加' + showText" :visible.sync="adddialogVisible" width="50%" @close="addClose">
      <el-form :model="addForm" :rules="addRuleForm" ref="addRuleFormRef" label-width="140px" class="demo-ruleForm">
        <el-form-item :label="'添加' + showText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsItem">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数 -->
    <el-dialog :title=" '编辑' + showText" :visible.sync="editdialogVisible" width="50%" @close="editClose">
      <el-form :model="editForm" :rules="editRuleForm" ref="editRuleFormRef" label-width="140px" class="demo-ruleForm">
        <el-form-item :label="'添加' + showText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsItem">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      selectKeys: [],
      cateDefaultOptions: [],
      activeName: 'many',
      cateId: '',
      manyData: [], // 动态参数
      onlyData: [], // 静态属性
      adddialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addRuleForm: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      editdialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editRuleForm: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    isBtn () {
      if (this.selectKeys.length === 3) {
        return false
      } else {
        return true
      }
    },
    showText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  methods: {
    // 获取分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateDefaultOptions = res.data
    },
    // 层级联动
    handleChange () {
      console.log(this.selectKeys)
      if (this.selectKeys.length === 3) {
        this.cateId = this.selectKeys[2]
        this.getParamData()
      } else {
        this.manyData = []
        this.onlyData = []
      }
    },
    // tab栏切换
    handleClick () {
      this.getParamData()
      console.log(this.activeName)
    },
    // 获取参数信息
    async getParamData () {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.map(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },
    // 添加参数
    addParams () {
      this.adddialogVisible = true
    },
    // 添加参数的dialog关闭后重置表单
    addClose () {
      this.$refs.addRuleFormRef.resetFields()
    },
    // 添加参数项
    addParamsItem () {
      this.$refs.addRuleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status === 201) {
          this.$message.success(res.meta.msg)
          this.getParamData()
        } else {
          this.$message.error(res.meta.msg)
        }
        this.adddialogVisible = false
      })
    },
    // 编辑参数
    async editParams (row) {
      this.editdialogVisible = true
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${row.attr_id}`)
      if (res.meta.status === 200) {
        this.editForm = res.data
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    // 编辑参数的dialog关闭后重置表单
    editClose () {
      this.$refs.editRuleFormRef.resetFields()
    },
    // 编辑参数项
    async editParamsItem () {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
        attr_name: this.editForm.attr_name,
        attr_sel: this.activeName
      })
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
        this.getParamData()
        this.editdialogVisible = false
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    // 删除
    deleteParams (row) {
      this.$confirm('此操作将永久删除参数项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
        if (res.meta.status === 200) {
          this.getParamData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } else {
          this.$message({
            errror: 'info',
            message: res.meta.msg
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除参数调用接口
    async deleteParamsVale (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
        this.getParamData()
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    // input移除光标
    handleInputConfirm (row) {
      if (row.inputValue.length !== 0) {
        row.attr_vals.push(row.inputValue)
        this.deleteParamsVale(row)
      }
      row.inputVisible = false
      row.inputValue = ''
    },
    // 显示input框
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除参数
    handleClose (row, i) {
      row.attr_vals.splice(i, 1)
      this.deleteParamsVale(row)
    }
  }
}
</script>

<style lang="less" scoped>
  .el-alert {
    margin: 20px 0;
  }
  .cate-wrap {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .el-cascader {
      width: 30%;
    }
  }
  .el-tag {
    margin: 0 10px;
  }
  .input-new-tag {
    width: 180px;
  }
</style>
